/*
 * 文件名：MallCartController.java
 * 版权：Copyright by hlst
 * 描述：
 * 修改人：liuziyu
 * 修改时间：2016年7月14日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.owner.controller.mall;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.model.mall.OwnerAddress;
import com.zcsy.manage.model.mall.ShoppingCart;
import com.zcsy.manage.model.mall.vo.CouponInfoVo;
import com.zcsy.manage.model.mall.vo.ShoppingCartVo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.owner.service.common.IOCommonTokenService;
import com.zcsy.manage.service.base.ICommonConfigService;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IGoodsSpecificationService;
import com.zcsy.manage.service.mall.IOrderInfoService;
import com.zcsy.manage.service.mall.IOwnerAddressService;
import com.zcsy.manage.service.mall.IShoppingCartService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title: ShoppingCartController.java
 * @Package： com.zcsy.manage.owner.controller.mall 
 * @Description: 购物车控制层
 * @author liuziyu liuziyuwri@foxmail.com
 * @Copyright: 2016 武汉恒数利通软件有限公司 All rights reserved.
 * @date 2016年7月14日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "ShoppingCart")
public class ShoppingCartController {

	@Autowired
	private IOCommonTokenService commonTokenService;
	
	@Autowired
	private IShoppingCartService shoppingCartService;
	
	@Autowired
	private IGoodsSpecificationService specService;
	
	@Autowired
	private IGoodsInfoService goodsInfoService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IOwnerAddressService ownerAddressService;
	
	@Autowired
	private IOrderInfoService orderInfoService;
	
	@Autowired
	private ICommonConfigService commonConfigService;
	
	@Autowired
	private ICouponDetailService couponInfoService;

	/**
	 * @Method: setGoodsNum
	 * @Description 编辑购物车商品数量
	 * @param cartId 购物车id
	 * @param token
	 * @param operateType 操作类型：1增加， 0指定数量， -1减少
	 * @param setAmount 指定的数量（为null时为其他操作方式）
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月14日
	 * @see 
	 */
	@RequestMapping(value = "setGoodsNum")
	@ResponseBody
	public RequestJson setGoodsNum(String cartId, String token,
			Integer operateType, Integer setAmount) {
		RequestJson result = new RequestJson();

		// 操作类型为增加数量
		if (operateType == OwnerConstants.ADD_AMOUNT && setAmount == null) {
			shoppingCartService.addAmount(cartId);
			ShoppingCart shoppingCart = shoppingCartService.getCartInfo(
					cartId);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("商品数量加1！");
			result.setObj(shoppingCart);

			// 操作类型为减少数量
		} else if (operateType == OwnerConstants.REDUCE_AMOUNT
				&& setAmount == null) {
			ShoppingCart shoppingCart = shoppingCartService.getCartInfo(
					cartId);
			Integer amount = shoppingCart.getAmount();
			// 如果商品数量小于等于1
			if (amount <= OwnerConstants.BASE_AMOUNT) {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("商品数量至少为1！");
			} else {
				shoppingCartService.reduceAmount(cartId);
				ShoppingCart shoppingCartNew = shoppingCartService.getCartInfo(
						cartId);
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("商品数量减1！");
				result.setObj(shoppingCartNew);

			}
			// 手动设置商品数量
		} else if (operateType == OwnerConstants.SET_AMOUNT
				&& setAmount != null && setAmount >= OwnerConstants.BASE_AMOUNT) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cartId", cartId);
			map.put("setAmount", setAmount);
			shoppingCartService.setAmount(map);
			
			ShoppingCart shoppingCartNew = shoppingCartService.getCartInfo(
					cartId);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功设置商品数量！");
			result.setObj(shoppingCartNew);
		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("入参格式有误！");
		}
		return result;
	}

	/**
	 * @Method: removeGoods
	 * @Description 移除购物车商品
	 * @param cartId 购物车id
	 * @param token
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月15日
	 * @see 
	 */
	@RequestMapping(value = "removeGoods")
	@ResponseBody
	public RequestJson removeGoods(String cartId, String token) {
		RequestJson result = new RequestJson();
		// 判断是否删除成功
		Integer state = null;

		// 将传入的多个购物车id进行拆分
		String[] cartIdArray = cartId.split(",");
		if (ArrayUtils.isNotEmpty(cartIdArray)) {
			// 将每个商品移除出购物车
			for (String singleCartId : cartIdArray) {
				state = shoppingCartService.deleteByPrimaryKey(singleCartId);
				// 判断是否删除成功
				if (state == OwnerConstants.NO_RECORD) {
					break;
				}
			}
			if (state == OwnerConstants.NO_RECORD) {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("删除部分商品失败（无此购物车id）！");
			} else {
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("成功移除该商品！");

			}
		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("请指定购物车id！");

		}
		return result;
	}

    /**
     * @Description 加入购物车<br>
     * 
     * @param token token标示
     * @param goodsId 商品id
     * @param spectificationId 规格id
     * @param amount 商品数量
     * @param type 1:购物车 2:立即购买
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月15日
     * @see 
     */
    @RequestMapping(value = "addToCart")
    @ResponseBody
    public RequestJson addToCart(String token,String goodsId,String spectificationId,Integer amount,Integer type,String cellId) {

        RequestJson result = new RequestJson();
        try {
        	CommonToken commonToken = commonTokenService.selectByToken(token);
        	User user = new User();
        	if (commonToken != null) {
        		user = userService.selectByLoginName(commonToken.getAccount());
			}
            Map<String, Object> map = new HashMap<String, Object>();
            Object flag = Constants.SQL_RESULT_ERROR;

            //判断所选规格是否存在库存，若没有，给出提示并且退出
            GoodsSpecification spec = specService.getGoodsSpecificationById(spectificationId);
            
            //若该商品没有规格，判断该商品是否有库存，若没有，给出提示并且退出
            GoodsInfo goods = goodsInfoService.getGoodsInfoByPrimaryKey(goodsId);
            Integer userCartNum = shoppingCartService.getUserCartNum(commonToken.getAccount());
            if (userCartNum>= Constants.SHOPPING_CART_MAX_NUM) {
            	result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
        		result.setMsg("超出购物车添加商品上限50");
        		result.setSuccess(false);
        		return result;
			}
            
            if (spec != null) {
				
            	if (spec.getStock() < amount) {
            		result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
            		result.setMsg("该规格库存不足，操作失败");
            		result.setSuccess(false);
            		return result;
            	}
			}else{
        		if (goods != null) {
                	
                	if (goods.getState() != Constants.GOODS_SALE) {
                		result.setMsg("该商品已下架");
                		result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                		result.setSuccess(false);
                		return result;
                	}else{
                		if (goods.getStock() < amount) {
                			result.setMsg("商品库存不足，操作失败");
                			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                			result.setSuccess(false);
                			return result;
                		}
                	}
    			}else{
    				result.setMsg("该商品不存在");
        			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
        			result.setSuccess(false);
        			return result;
    			}

        	}
            
            flag = shoppingCartService.addToCart(user.getLoginname(), goodsId, spectificationId, amount,type,goods,spec,cellId);

            if (flag == (Object)OwnerConstants.NO_ENOUGH_GOODS) {
                result.setMsg("商品库存不足，操作失败");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
            } else if (flag == (Object)Constants.SQL_RESULT_ERROR) {
                result.setMsg("添加失败");
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setSuccess(false);
                return result;
            } else {
                map.put("id", flag);
                result.setMsg("添加成功");
                result.setObj(map);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setSuccess(true);
                return result;
            }

        } catch (Exception e) {
            result.setMsg("操作异常");
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
            e.printStackTrace();
        }
        return result;
        
    }
    
    /**
     * @Description 去结算接口<br>
     * 
     * @param ids 已选购物车id集合
     * @param token token标示
     * @param type 类型：1;正常商品  2;积分商品  3;秒杀商品
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月15日
     * @see 
     */
    @RequestMapping(value = "getSelectedCart")
    @ResponseBody
    public RequestJson getSelectedCart(String ids,String token , int type) {

        RequestJson result = new RequestJson();
        
        List<ShoppingCart> cartList = new ArrayList<ShoppingCart>();
        Map<String, Object> map = new HashMap<String, Object>();

        try {
        	CommonToken commonToken = commonTokenService.selectByToken(token);
        	User user = new User();
        	if (commonToken != null) {
        		user = userService.selectByLoginName(commonToken.getAccount());
			}
            if (ids != null && ids.length() > 0) {
                String[] id = ids.split(",");
                cartList = shoppingCartService.getSettleCarts(id);
                
                RequestJson req = shoppingCartService.checkSubmitOrder(cartList, user);
            	if(req != null){
                	return req;
                }
            	
            	List<OwnerAddress> addresList = ownerAddressService.getOwnerAddressByOwnerId(user.getId());
                OwnerAddress currentRecord = null;
                for (OwnerAddress address : addresList) {
                    if (address.getDefaultFlag() == OwnerConstants.DEFAULT_ADDRESS) {
                        currentRecord = address;
                    }
                }

                if (currentRecord == null && addresList != null && addresList.size() > 0) {
                    currentRecord = addresList.get(0);
                }
                
                map.put("normal_carriage_line", commonConfigService.getByName("normal_carriage_line").getValue());
                map.put("normal_carriage_y", commonConfigService.getByName("normal_carriage_y").getValue());
                map.put("normal_carriage_n", commonConfigService.getByName("normal_carriage_n").getValue());
                map.put("seckill_carriage", commonConfigService.getByName("seckill_carriage").getValue());
                map.put("cards_carriage", commonConfigService.getByName("cards_carriage").getValue());
                map.put("cartList", cartList);
                map.put("defAddres", currentRecord);
                if(type == Constants.GOODS_TYPE_NORMAL){
                	map.put("coupons", getAvaliabelCoupon(user, ids, type));
                }
                
                if (map != null && !map.isEmpty()) {
                    result.setObj(map);
                    result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                    result.setSuccess(true);
                } else {
                    result.setSuccess(false);
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("未获取数据");
                }
            }else{
            	result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("未获取数据");
            }
         } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
            result.setMsg("操作异常");
        }
        return result;
    }
    
    
    /** 
     * @Title: confirmOrder 
     * @Description: 提交订单
     * @param @param maps 各商家信息封装
     * @param @param token 用户token
     * @param @param cellId 小区ID
     * @param @param shopcartIds 购物车ID，英文逗号分隔
     * @param @param request
     * @param @return     
     * @return RequestJson     
     * @throws 
     */
    @RequestMapping(value = "confirmOrder", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson confirmOrder(@RequestBody List<Map<String, Object>> maps,String token,String cellId , String shopcartIds , HttpServletRequest request){
    	RequestJson result = new RequestJson();
    	StringBuffer couponIds = new StringBuffer();
    	String couponIdStr = null;
    	try{
    		CommonToken commonToken = commonTokenService.selectByToken(token);
    		User user = new User();
    		if (commonToken != null) {
    			user = userService.selectByLoginName(commonToken.getAccount());
    			CellInfo cell = new CellInfo();
    			cell.setId(cellId);
    			user.setCurrentCell(cell);
    		}
    		
    	List<ShoppingCart> cartList = shoppingCartService.getSettleCarts(shopcartIds.split(","));
    	RequestJson req = shoppingCartService.checkSubmitOrder(cartList, user);
    	if(req != null){
        	return req;
        }
    	
    	int type = cartList.get(0).getGoodsType();
    	
    	// 转化页面视图显示
        List<ShoppingCartVo> shopcart = shoppingCartService.castShoopingCartVo(cartList, cartList.get(0).getGoodsType());
    	
    	List<OrderInfo> orderInfo = new ArrayList<OrderInfo>();
    	for(Map<String, Object> item : maps){
    		OrderInfo info = new OrderInfo();
    		info.setShopId((String)item.get("shopId"));
    		
    		ShoppingCartVo cart = null;
    		for(ShoppingCartVo itemVo : shopcart){
    			if((StringUtils.isEmpty(itemVo.getShopId()) && StringUtils.isEmpty(info.getShopId()))
    					|| itemVo.getShopId().equals(info.getShopId())){
    				cart = itemVo;
    				break;
    			}
    		}
    		
    		if(!StringUtils.isEmpty(item.get("msg"))){
    			info.setShopMsg((String)item.get("msg"));
    		}
    		
    		if(!StringUtils.isEmpty(item.get("distributionType"))){
    			info.setDistributionType((Integer)item.get("distributionType"));
    			info.setIsBySelf(info.getDistributionType() == Constants.DISTRIBUTION_COMPANY ? Constants.IS_BYSELF_N : Constants.IS_BYSELF_Y);
    		}else{
    			info.setDistributionType(Constants.IS_HAS_DISN_N);
    			info.setIsBySelf(Constants.IS_BYSELF_N);
    		}
    		if(!StringUtils.isEmpty(item.get("expectTime"))){
    			info.setExpectTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse((String)item.get("expectTime")));
    		}
			info.setCarriage(cart.getCarriage());
			info.setCouponPrice(new BigDecimal(0));//service里面算
			info.setTotalPrice(cart.getSubTotal());
			
			if(!StringUtils.isEmpty(item.get("couponId"))){
				info.setCouponId((String)item.get("couponId"));
				couponIds.append(",");
				couponIds.append((String)item.get("couponId"));
    		}
			
			if(!StringUtils.isEmpty(item.get("addrId"))){
				info.setRectAddrId((String)item.get("addrId"));
			}
			
			orderInfo.add(info);
    	}
    	
    	if(couponIds.length() > 0){
    		//去掉第一个逗号
			couponIdStr = couponIds.substring(1).toString();
    		//将优惠券id放入第一位
	    	orderInfo.get(0).setCouponId(couponIdStr);
    	}
    	
    	OrderInfo initInfo = shoppingCartService.confirmOrderFromShopcart(shopcartIds, user, orderInfo , type);
    	
    	result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
    	result.setSuccess(true);
		result.setObj(initInfo);
		
    	}catch(Exception e){
    		e.printStackTrace();
    		result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
    		result.setMsg("操作失败");
    		result.setSuccess(false);
    	}
    	
    	return result;
    }
    
	/** 
	 * @Title: getAvaliabelCoupon 
	 * @Description: TODO
	 * @param @param token 用户登录标识
	 * @param @param shopcartIds 购物车IDS
	 * @param @param type 1;正常商品  2;积分商品  3;秒杀商品
	 * @param @return     
	 * @return List<CouponInfoVo>     
	 * @throws 
	 */
	public List<CouponInfoVo> getAvaliabelCoupon(User user,String shopcartIds , int type){
    	
    	try{
    	List<ShoppingCart> cartList = shoppingCartService.getSettleCarts(shopcartIds.split(","));
        
    	if(cartList == null || cartList.size() == 0){
    		return null;
    	}
    	
		List<ShoppingCartVo> shopcart = null ;
        shopcart = shoppingCartService.castShoopingCartVo(cartList, type);
        
        BigDecimal total = getTotal(shopcart);
        BigDecimal carriageTotal = BigDecimal.ZERO;
        BigDecimal derateTotal = BigDecimal.ZERO;
        StringBuilder shopIds = new StringBuilder();
        for(ShoppingCartVo vo : shopcart) {
            carriageTotal = carriageTotal.add(vo.getCarriage());
            derateTotal = derateTotal.add(vo.getDerateAmount());
            shopIds.append(vo.getShopId()).append(",");
        }
    	
    	// 优惠券信息
        List<CouponInfoVo> couponList = couponInfoService.getAvaliabelCoupon(total, shopcart, shopIds.toString(), user.getLoginname());
        return couponList;
		
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	
    	return null;
    }
    
    private BigDecimal getTotal(List<ShoppingCartVo> list) {
        BigDecimal result = BigDecimal.ZERO;
        for(ShoppingCartVo vo : list) {
            BigDecimal shopTotal = BigDecimal.ZERO;
            for(ShoppingCart cart : vo.getGoodsList()) {
                shopTotal = shopTotal.add(cart.getSubTotal());
            }
            result = result.add(shopTotal);
        }
        return result;
    }
}
